package vn.allmobile.ambnews.activities.category;

import java.util.List;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.aphidmobile.flip.FlipViewController;
import vn.allmobile.ambnews.AboutActivity;
import vn.allmobile.ambnews.BaseActivity;
import vn.allmobile.ambnews.R;
import vn.allmobile.ambnews.SettingsActivity;
import vn.allmobile.ambnews.customview.FlipViewInterface;
import vn.allmobile.ambnews.data.Category;
import vn.allmobile.ambnews.data.Paper;
import vn.allmobile.ambnews.flipview.FlipView;
import vn.allmobile.ambnews.flipview.OverFlipMode;
import vn.allmobile.ambnews.network.LoadDataListener;
import vn.allmobile.ambnews.network.NetworkAPI;
import vn.allmobile.ambnews.network.NetworkChangeReceiver;
import vn.allmobile.ambnews.utils.Contants;
import vn.allmobile.ambnews.utils.Log;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import vn.allmobile.ambnews.activities.list.ListActivity;
import vn.allmobile.ambnews.activities.main.MainAllPapersActivity;
import android.annotation.TargetApi;
import android.content.Intent;
import android.view.View;
import android.widget.Toast;

public class CategoryActivity extends BaseActivity implements LoadDataListener {
	
	int _paperIndex;
	FlipViewInterface flipview;
	//FlipView flipview;
	CategoryFlipViewAdapter adapter;
	List<Category> categories;
	Boolean isUserPaper = false;
	Boolean updating = false;
	int numTask = 0;
	int numTaskComplete = 0;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_category);
		_paperIndex = NetworkAPI._currentPaperIndex;
		Intent intent = getIntent();
		
		String category_type = intent.getStringExtra(Contants.EXTRA_CATEGORY_TYPE);		
		Paper pp = null;
		if(category_type != null && category_type.equals(Contants.CATEGORY_TYPE_USER_PAPER))
		{
			Log.v("category_type:" + category_type);
			pp = NetworkAPI._userListPapers.get(_paperIndex);
			isUserPaper = true;
		}
		else
		{
			isUserPaper = false;
			pp = NetworkAPI._papers.get(_paperIndex);
		}
			
		categories = pp.getCategories();
		
		try{
			flipview = (FlipView )findViewById(R.id.flipViewCategory);	
			flipview.setOverFlipMode(OverFlipMode.RUBBER_BAND);
		}catch(Exception e) 
		{
			flipview = (FlipViewController)findViewById(R.id.flipViewCategory);
		}
		//flipview = (FlipView)findViewById(R.id.flipViewCategory);			
		
		adapter = new CategoryFlipViewAdapter(this,categories,this,isUserPaper);
		adapter._flipview = flipview;
		
		flipview.setAdapter(adapter);
		
		//flipview.setOnFlipListener(this);
		
	}

	/*@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.main,  menu);
		return super.onCreateOptionsMenu(menu);
		
	}


		

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
			case R.id.menu_settings:
			 Intent mIntent_setting = new Intent(getApplicationContext(), SettingsActivity.class);			
			 startActivity(mIntent_setting);
			return true;
			case R.id.menu_paper_manage:
				 Intent mIntent = new Intent(getApplicationContext(), MainAllPapersActivity.class);			
				 startActivity(mIntent);
				return true;
			case R.id.menu_exits:
				android.os.Process.killProcess(android.os.Process.myPid());
				return true;
			case R.id.menu_about:
				 Intent intent = new Intent(getApplicationContext(), AboutActivity.class);			
				 startActivity(intent);
			default :
				return super.onMenuItemSelected(featureId, item);
	}
		
	}*/
	@Override
	public void onPaperloadSuccess() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onCategoryloadSuccess() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onListloadSuccess() {
		// TODO Auto-generated method stub
		//Log.v("onListloadSuccess");
		//flipview = (FlipViewInterface)findViewById(R.id.flipViewCategory);
		//adapter = (CategoryFlipViewAdapter) flipview.getAdapter();
		adapter.notifyDataSetChanged();
	    //adapter.notifyDataSetInvalidated();	   
	}
	
	public Handler mHandle = new Handler()
	  {
	    public void handleMessage(Message paramAnonymousMessage)
	    {
	      switch (paramAnonymousMessage.what)
	      {	      
		      case 0:
		    	  CategoryActivity.this.startListActivity();
		      break;	  
		      case 1:
		    	  Toast.makeText(CategoryActivity.this, "Không có kết nối mạng", Toast.LENGTH_LONG).show();
		    	 break; 
		      default:
	      }
	      
	    }
	  };
	protected void startListActivity() {
		// TODO Auto-generated method stub
		Intent localIntent = new Intent(this, ListActivity.class);
	   // localIntent.addFlags(FLAGS_MAIN_ACITIVTY);
	    startActivity(localIntent);
	    finish();
	}
	


	@Override
	  protected void onResume() {
		 super.onResume();
	    flipview.refreshAllPages();	   
	    flipview.onResume();
	    updating = false;
	    numTask = 0;
		numTaskComplete = 0;
	    try{
	    	for(Category cat : categories){
				cat.setUpdating(false);
			}
	    }catch(Exception e){
	    	
	    }
	    
	  }

	  @Override
	  protected void onPause() {
	    super.onPause();
	    flipview.onPause();	    
	  }
	  
	  @Override
	  protected void onDestroy() {
		  super.onDestroy();		 
	  }

	@Override
	public void onListloadFail() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onUserloadSuccess() {
		// TODO Auto-generated method stub
		
	}
	
	
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	public void onRefresh(View v){
		if(NetworkChangeReceiver.isConnected(true))		
			if(updating == false)
			{
				updating = true;
				int index = 0;
				for(Category cat : categories)
				{
					numTask ++ ;
					refreshTask task  = new refreshTask(index,cat.getId());					
					if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB) {				
						task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
					}
					else {				
						task.execute();
					}
					index ++;
				}
			}	
		
	}
	
	
	private class refreshTask extends AsyncTask<Void, Boolean, Boolean> {

		int categoryIndex;
		String categoryId;
		
		refreshTask(int categoryIndex, String categoryId)
		{
			this.categoryIndex = categoryIndex;
			this.categoryId 	= categoryId;
		}
		@Override
		protected void  onPreExecute()
		{			
			categories.get(categoryIndex).setUpdating(true);			
			adapter.notifyDataSetChanged();
			super.onPreExecute();			
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			if(updating)
			{
				Log.v("onPostExecute :categoryIndex:" + categoryIndex);
				categories.get(categoryIndex).setUpdating(false);
				// TODO Auto-generated method stub
				adapter.notifyDataSetChanged();	
				numTaskComplete ++;
				if(numTask <= numTaskComplete)
				{
					updating = false;
				}
				//mAdapter.notifyDataSetInvalidated();
			}
			
			//flipview.refreshPage(0);
			super.onPostExecute(result);
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			if(updating)
			{
				Log.v(NetworkAPI._currentPaperId);
				//Log.v( categoryId);
				//LoaderThread loader = new LoaderThread();
				NetworkAPI._()._loaderThread.loadListArticle(NetworkAPI._currentPaperId,categoryId,true);
			}												
			return true;
		}				
	}
	
	
	public void onBackClick(View v){
		onBackPressed();
		overridePendingTransition(R.anim.grow_from_bottom,R.anim.slide_out_right);
	}
	
	public void onSettingClick(View v)
	{
		Intent mIntent = new Intent(this, SettingsActivity.class);			
		startActivity(mIntent);
	}
	
	public void onMoreClick(View v)
	{
		Intent mIntent = new Intent(this, MainAllPapersActivity.class);			
		startActivity(mIntent);	
	}
}
